package com.sumainfor.pc.dev.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.*;
import com.sumainfor.pc.dev.dao.CouponLogMapper;
import com.sumainfor.pc.dev.dao.CouponMapper;
import com.sumainfor.pc.dev.dao.UtilsMapper;
import com.sumainfor.pc.dev.service.CouponLogService;
import com.sumainfor.pc.dev.service.CouponService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 优惠券创建记录
 * <p>
 *
 * @author: zhoucong
 * @create: 2019-05-05 11:07
 **/
@Service
public class CouponLogServiceImpl implements CouponLogService {


    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(CouponLogServiceImpl.class);

    @Autowired
    CouponLogMapper couponLogMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    CouponService couponService;
    /**
    * <p>
    * 查询优惠券同一批次下优惠券不同的类型
    * </p>
    *
    * @author: zhoucong
    * @since:
    */
    @Override
    public JsonResult getCouponLogCouType(Map<String,Object> params, Pager pager){
        JsonResult result = new JsonResult();
        pager.setPagerNecessary(params,pager);
        PageUtils pageUtils = new PageUtils();
        Integer cout = couponLogMapper.getCouponLogCouTypeCount(params);
        System.out.println("cout"+cout);
        if(cout == 0){
            return pageUtils.getJsonResult(new ArrayList<Map<String,Object>>(),params,cout);
        }else {
            List<Map<String, Object>> couponLogList = couponLogMapper.getCouponLogCouType(params);
            for (Map<String,Object> couponLogMap:couponLogList) {
                Integer CouponStatusCount = couponMapper.getCouponBatIdCount(couponLogMap);
                couponLogMap.put("CouponStatusCount",CouponStatusCount);
            }
            return pageUtils.getJsonResult(couponLogList,params,cout);
        }
    }

    /**
    * <p>
    * 创建优惠券（批次）
    * </p>
    *
    * @author: zhoucong
    * @since:
    */
    @Override
    public JsonResult insertCouponLog(Map<String,Object> params){
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
           Map<String,Object> CouponMap = new HashMap<>();
           CouponMap.put("CouName",params.get("CouName"));
            CouponMap.put("CouType",params.get("CouType"));
            Integer CouponMapCount = couponLogMapper.getCouponRepeat(CouponMap);
            if (CouponMapCount>0){
                result.putFailed("不能创建相同的优惠券名字和类型!");
            }else {

                log.info("增加操作");
                params.put("term", "1");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                String UUID;
                Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "CouBatId");
                    put("database", Constants.DATA_SOURCE_TCDP);
                    put("surface", "tcdp_coupon_log");
                }});
                if (uuid != null) {
                    int number = Integer.valueOf(uuid.get("uuid").toString());
                    UUID = ComUtils.getLocalTrmSeqNum("yhq", number);
                } else {
                    UUID = ComUtils.getLocalTrmSeqNum("yhq", 0);
                }
                params.put("CouBatId", UUID);
                params.put("CreationTime", ConvertDateTime.getCurrentTime());
                Integer cout = couponLogMapper.insertCouponLog(params);
                if (cout <= 0) {
                    result.putFailed("创建失败!");
                } else {
                    int zczs = MapUtils.getInteger(params, "Circulation").intValue();
                    for (int i = 1; i <= zczs; i++) {
                        params.put("CouId", ComUtils.randomUID());
                        couponService.insertCoupon(params);
                    }
                    result.putSuccess("创建成功!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;

    }


}
